package com.service.impl;

import cn.hutool.core.util.StrUtil;
import com.constant.URLConstant;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiUserGetRequest;
import com.dingtalk.api.request.OapiUserGetuserinfoRequest;
import com.dingtalk.api.response.OapiUserGetResponse;
import com.dingtalk.api.response.OapiUserGetuserinfoResponse;
import com.entity.User;
import com.mapper.UserMapper;
import com.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.taobao.api.ApiException;
import com.util.AccessTokenUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


/**
 * <p>
 * 上报人表 服务实现类
 * </p>
 *
 * @author 马磊
 * @since 2023-02-10
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Value("${dd.key}")
    private String key;

    @Value("${dd.secret}")
    private String secret;
    /**
     *
     * @param authCode
     * @return
     */
    @Override
    public User login(String authCode) {
        if (StrUtil.isEmpty(authCode) || StrUtil.isBlank(authCode)){
            return new User();
        }
        String accessToken;
        try {
            //获取accessToken
            accessToken = AccessTokenUtil.getToken(key,secret);
        } catch (RuntimeException e) {
            e.printStackTrace();
            return new User();
        }
        //获取用户信息
        DingTalkClient client = new DefaultDingTalkClient(URLConstant.URL_GET_USER_INFO);
        OapiUserGetuserinfoRequest request = new OapiUserGetuserinfoRequest();
        request.setCode(authCode);
        request.setHttpMethod("GET");

        OapiUserGetuserinfoResponse response;
        try {
            response = client.execute(request, accessToken);
        } catch (ApiException e) {
            e.printStackTrace();
            return new User();
        }
        String userId = response.getUserid();
        String userName = getUserName(accessToken, userId);
        //返回结果
        return new User(userId,userName);
    }

    /**
     * 获取用户姓名
     * @param accessToken
     * @param userId
     * @return
     */
    private String getUserName(String accessToken, String userId) {
        try {
            DingTalkClient client = new DefaultDingTalkClient(URLConstant.URL_USER_GET);
            OapiUserGetRequest request = new OapiUserGetRequest();
            request.setUserid(userId);
            request.setHttpMethod("GET");
            OapiUserGetResponse response = client.execute(request, accessToken);
            return response.getName();
        } catch (ApiException e) {
            e.printStackTrace();
            return null;
        }
    }
}
